package cn.luckdou.WeChat.utils;

import cn.luckdou.WeChat.config.WxMpConfig;
import cn.luckdou.commons.utils.MyJsdisUtil;
import net.sf.json.JSONObject;

import java.util.Date;

public class JsapiTicketUtils {
    private static Long t=1000L*60L*100L;


    public static String getJsapiTicket(){
        String Jsapi_Ticket = (String) MyJsdisUtil.get("Jsapi_Ticket");
        Long Jsapi_Ticket_time = (Long) MyJsdisUtil.get("Jsapi_Ticket_time");
        if (Jsapi_Ticket==null || Jsapi_Ticket_time==null){
            return setJsapiTicket();
        }
        if (new Date().getTime()-Jsapi_Ticket_time<=t){
            //没有过期
            return Jsapi_Ticket;
        }else{
            return setJsapiTicket();
        }
    }

    public static String getNewJsapiTicket(){
        return setJsapiTicket();
    }

    private static String setJsapiTicket() {
        try{
            System.out.println(AccessTokenUtils.getNewToken());
            String Jsapi_Ticket_json = HttpUtils.sendGet(WxMpConfig.getJsapi_ticket(AccessTokenUtils.getToken()));
            String Jsapi_Ticket = JSONObject.fromObject(Jsapi_Ticket_json).getString("ticket");
            MyJsdisUtil.set("Jsapi_Ticket",Jsapi_Ticket);
            MyJsdisUtil.set("Jsapi_Ticket_time",new Date().getTime());
            return Jsapi_Ticket;
        }catch (Exception e){
            return null;
        }
    }

}
